package com.jiefutong.zyt.http.view;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by admin on 2017/2/11.
 */

public class RequestCallBackApi<T> implements Callback<T> {
    private IRequestView view;

    public RequestCallBackApi(IRequestView view) {
        this.view = view;
    }

    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        if (response.isSuccessful()) {
            T v = (T) response.body();
            view.onSuccess(v);
           /* if (response.isSuccessful()) {
                view.onSuccess(v);
            } else {
                view.onFailure(v.getMsg());
            }*/
        } else {
            String error = response.message();

            try {
                /*JSONObject jsonObject = new JSONObject(response.errorBody().string());
                if (!TextUtils.isEmpty(jsonObject.getString("msg"))) {
                    error = jsonObject.getString("msg");
                }*/
                error =response.errorBody().string();
            } catch (Exception e) {
                e.printStackTrace();
            }
            view.onFailure("请求失败(" + response.code() + ") ：" + error);
        }
        view.afterRequest();
        call.cancel();
    }

    @Override
    public void onFailure(Call<T> call,Throwable t) {
        view.onFailure("请求失败：" + t.getMessage());
        view.afterRequest();
        call.cancel();
    }
}
